﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

using Recon.Portal.Business;
using Recon.Portal.DataObjects;

namespace Recon.Portal.WebUI
{
    public partial class RemitterMatchInvoice : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GetInvoiceList();
                GetStatementList();
            }
        }

     /*   protected void btnMarkPayment_Click(object sender, EventArgs e)
        {
            List<MatchedInvoice> dtInvoice = (List<MatchedInvoice>)Session[SessionStore.UnMatchedInvoiceListForRemitter];
            if (dtInvoice != null && dtInvoice.Count<MatchedInvoice>() > 0)
            {
                string paymentReferenceNumber = txtPaymentReferenceNumber.Text;
                ReconcileEntity recon = new ReconcileEntity();
                List<Statement> statements = recon.GetStatementDetailsForRemitter(((User)Session["CurrentUserVO"]).CustomerID, paymentReferenceNumber);
                if (statements != null && statements.Count<Statement>() > 0)
                {
                    //count marked entries, if 0 then no change in session object and UI
                    int ctr = 0;
                    foreach (GridViewRow invoiceRow in grdInvoice.Rows)
                    {
                        CheckBox chkSelect = (CheckBox)invoiceRow.Cells[0].FindControl("chkSelect");
                        if (chkSelect.Checked)
                        {
                            dtInvoice[invoiceRow.RowIndex].ReferenceNumber = paymentReferenceNumber;
                            dtInvoice[invoiceRow.RowIndex].StatementUniqueID = statements[0].StatementID;
                            dtInvoice[invoiceRow.RowIndex].StatementAmount = statements[0].amount;
                            ctr++;
                        }
                    }

                    //if counter > 0 then update session object and UI
                    if (ctr > 0)
                    {
                        Session[SessionStore.UnMatchedInvoiceListForRemitter] = dtInvoice;
                        grdInvoice.DataSource = dtInvoice;
                        grdInvoice.DataBind();
                        btnConfirmMatches.Visible = true;
                    }
                    else
                    {//no marked entries
                    }
                }
                else
                {//no statement entry found
                }
            }
        }
        */
      
        private void ShowMatchedList()
        {
        }

        private void MatchManually(List<Invoice> dtInvoice, List<Statement> dtStatement)
        {
            List<string> successMatchType = new List<string>();
            List<MatchedInvoice> matchList = new List<MatchedInvoice>();
            ReconcileEntity reconEntity = new ReconcileEntity();

            // if (matchType == "Manual")
            {

                int invoiceRowNumber = 0, statementRowNumber = 0, invoiceAdded = 0, statementAdded = 0;
                double totalInvoiceAmount = 0.00, totalStatementAmount = 0.00;

                foreach (GridViewRow invoiceRow in grdInvoice.Rows)
                {
                    invoiceRowNumber++;
                    //System.Web.UI.HtmlControls.HtmlInputCheckBox chkSelect = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)invoiceRow.Cells[0].FindControl("chkSelect"));
                    CheckBox chkSelect = (CheckBox )invoiceRow.Cells[0].FindControl("chkSelect");
                 
                    if (chkSelect.Checked)
                    {
                        invoiceAdded++;

                        Literal ltlInvoiceUniqueID = ((Literal)invoiceRow.Cells[0].FindControl("ltlInvoiceUniqueID"));
                        MatchedInvoice inv = new MatchedInvoice();

                        inv.InvoiceUniqueID = ltlInvoiceUniqueID.Text;
                        inv.InvoiceNumber = invoiceRow.Cells[1].Text;

                        inv.InvoiceDate = DateTime.ParseExact(invoiceRow.Cells[2].Text, "dd-MM-yyyy", null);
                       // inv.InvoiceDate = Convert.ToDateTime(invoiceRow.Cells[2].Text);
                 //       inv.RemitterName = invoiceRow.Cells[3].Text;
                        inv.InvoiceAmount = Convert.ToDouble(invoiceRow.Cells[3].Text);
                       // inv.InvoiceAmountToReconcile = Convert.ToDouble(invoiceRow.Cells[6].Text);
                        inv.IsPartialInvoiceMatch = false;
                       
                        matchList.Add(inv);
                       // totalInvoiceAmount += inv.InvoiceAmountToReconcile;
                        totalInvoiceAmount += inv.InvoiceAmount;

                        dtInvoice.RemoveAt(invoiceRowNumber - invoiceAdded);
                    }
                }

                foreach (GridViewRow statementRow in grdStatement.Rows)
                {
                    statementRowNumber++;
                    System.Web.UI.HtmlControls.HtmlInputCheckBox chkSelect = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)statementRow.Cells[0].FindControl("chkSelect"));
                    if (chkSelect.Checked)
                    {
                        statementAdded++;

                        Literal ltlStatementUniqueID = ((Literal)statementRow.Cells[0].FindControl("ltlStatementUniqueID"));

                        if (statementAdded <= invoiceAdded)
                        {
                            MatchedInvoice match = matchList[statementAdded - 1];
                            match.StatementUniqueID = ltlStatementUniqueID.Text;
                            match.ReferenceNumber = statementRow.Cells[1].Text;
                            match.ValueDate = Convert.ToDateTime(statementRow.Cells[2].Text);
                            match.Narration1 = statementRow.Cells[3].Text;
                            match.StatementAmount = Convert.ToDouble(statementRow.Cells[4].Text);
                            match.StatementAmountToReconcile = Convert.ToDouble(statementRow.Cells[6].Text);
                            match.IsPartialStatementMatch = false;
                            totalStatementAmount += match.StatementAmountToReconcile;
                        }
                        else
                        {
                            MatchedInvoice match = new MatchedInvoice
                            {
                                StatementUniqueID = ltlStatementUniqueID.Text,
                                ReferenceNumber = statementRow.Cells[1].Text,
                                ValueDate = Convert.ToDateTime(statementRow.Cells[2].Text),
                                Narration1 = statementRow.Cells[3].Text,
                                StatementAmount = Convert.ToDouble(statementRow.Cells[4].Text),
                                StatementAmountToReconcile = Convert.ToDouble(statementRow.Cells[6].Text),
                                IsPartialStatementMatch = false
                            };
                            matchList.Add(match);
                            totalStatementAmount += match.StatementAmountToReconcile;
                        }

                        dtStatement.RemoveAt(statementRowNumber - statementAdded);
                    }
                }

                //show matched list on popup
                if (matchList.Count<MatchedInvoice>() > 0)
                {
                    //calculate amount to reconcile - if both total match then no change in AmountToReconcile
                    //else subtract the difference against the last item that's on the higher side
                    if (totalInvoiceAmount > totalStatementAmount)
                    {
                        matchList.Last<MatchedInvoice>().InvoiceAmountToReconcile -= totalInvoiceAmount - totalStatementAmount;
                        matchList.Last<MatchedInvoice>().IsPartialInvoiceMatch = true;
                    }
                    else if (totalInvoiceAmount < totalStatementAmount)
                    {
                        matchList.Last<MatchedInvoice>().StatementAmountToReconcile -= totalStatementAmount - totalInvoiceAmount;
                        matchList.Last<MatchedInvoice>().IsPartialStatementMatch = true;
                    }
                    reconEntity.MatchInvoicesForRemitter(matchList, ((User)Session["CurrentUserVO"]).CustomerID, ((User)Session["CurrentUserVO"]).UserID);
                }
                else
                {

                }

                Session["UnMatchedInvoiceList"] = dtInvoice;
                grdInvoice.DataSource = dtInvoice;
                grdInvoice.DataBind();

                Session["RemitUMStatementList"] = dtStatement;
                grdStatement.DataSource = dtStatement;
                grdStatement.DataBind();


            }
        }
        protected void btnConfirmMatches_Click(object sender, EventArgs e)
        {
            //List<MatchedInvoice> dtInvoiceList = (List<MatchedInvoice>)Session[SessionStore.UnMatchedInvoiceListForRemitter];

            List<Invoice> dtInvoiceList = (List<Invoice>)Session[SessionStore.UnMatchedInvoiceListForRemitter];
            List<Statement> dtStatement = (List<Statement>)Session["RemitUMStatementList"];

            MatchManually(dtInvoiceList, dtStatement);
            //ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('Invoice Entry');", true);
        }

        /// <summary>
        /// OLD method , not used now
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnConfirmMatches_Click_old(object sender, EventArgs e)
        {
            List<MatchedInvoice> dtInvoiceList = (List<MatchedInvoice>)Session[SessionStore.UnMatchedInvoiceListForRemitter];
            if (dtInvoiceList  != null && dtInvoiceList.Count<MatchedInvoice>() > 0)
            {
                List<MatchedInvoice> matchList = new List<MatchedInvoice>();

                for (int x = 0; x < dtInvoiceList .Count<MatchedInvoice>(); x++)
                {
                    if (!string.IsNullOrEmpty(dtInvoiceList [x].ReferenceNumber))
                    {
                        MatchedInvoice match = new MatchedInvoice
                        {
                            InvoiceUniqueID = dtInvoiceList [x].InvoiceUniqueID,
                            InvoiceNumber = dtInvoiceList [x].InvoiceNumber,
                            InvoiceDate = dtInvoiceList [x].InvoiceDate,
                            RemitterID = dtInvoiceList [x].RemitterID,
                            InvoiceAmount = dtInvoiceList [x].InvoiceAmount,
                            StatementUniqueID = dtInvoiceList [x].StatementUniqueID,
                            ReferenceNumber = dtInvoiceList [x].ReferenceNumber,
                            ValueDate = dtInvoiceList [x].ValueDate,
                            Narration1 = dtInvoiceList [x].Narration1,
                            StatementAmount = dtInvoiceList [x].StatementAmount,
                        };
                        matchList.Add(match);
                    }
                }

                if (matchList != null && matchList.Count<MatchedInvoice>() > 0)
                {
                    ReconcileEntity recon = new ReconcileEntity();
                    recon.MatchInvoicesForRemitter(matchList, ((User)Session["CurrentUserVO"]).CustomerID, ((User)Session["CurrentUserVO"]).UserID);

                    //Fetch updated list for remitter and update UI
                    GetInvoiceList();
                    GetInvoiceList();
                }
                else
                {
                }
            }
            //ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('Invoice Entry');", true);
        }

        protected void grdInvoice_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdInvoice.DataSource = (List<MatchedInvoice>)Session[SessionStore.UnMatchedInvoiceListForRemitter];
            grdInvoice.PageIndex = e.NewPageIndex;
            grdInvoice.DataBind();
        }

        protected void grdInvoice_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex > -1)
            {
                DateTime dt;
                if (e.Row.Cells[2].Text != "" && e.Row.Cells[2].Text != "&nbsp;")
                {
                    dt = Convert.ToDateTime(e.Row.Cells[2].Text);
                    e.Row.Cells[2].Text = dt.ToString("dd-MM-yyyy");
                    e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Center;
                }
                else
                {
                    e.Row.Cells[2].Text = "";
                }
               

                double value = 0.00;
                if (e.Row.Cells[3].Text != "" && e.Row.Cells[3].Text != "&nbsp;")
                {
                    value = Convert.ToDouble(e.Row.Cells[3].Text);
                    e.Row.Cells[3].Text = value.ToString("#,#.00", CultureInfo.InvariantCulture);
                    e.Row.Cells[3].HorizontalAlign = HorizontalAlign.Right;
                }
                else
                {
                    e.Row.Cells[3].Text = "0.00";
                }                

            }       
        }

        private void GetInvoiceList()
        {
            User user = (User)Session["CurrentUserVO"];
            Lists lstEntity = new Lists();
            List<Invoice> dtInvoice = lstEntity.GetUnmatchedInvoicesForRemitter(user.CustomerID, user.UserID);
            if (dtInvoice != null)
            {
                //Invoice data object doesn't contain all fields required for UI, so considering use of MatchedInvoice data object.
           /*     List<MatchedInvoice> invList = new List<MatchedInvoice>();
                foreach (Invoice inv in dtInvoice)
                {
                    MatchedInvoice mInvoice = new MatchedInvoice
                    {
                        InvoiceUniqueID = inv.InvoiceID,
                        InvoiceNumber = inv.InvoiceNumber,
                        InvoiceDate = inv.InvoiceDate,
                        RemitterID = inv.RemitterID,
                        InvoiceAmount = inv.Amount,
                        ReferenceNumber = inv.PORef
                    };
                    invList.Add(mInvoice);
                }
                //Storing in session object..........................
                Session[SessionStore.UnMatchedInvoiceListForRemitter] = invList;
                grdInvoice.DataSource = invList;
                */
                Session[SessionStore.UnMatchedInvoiceListForRemitter] = dtInvoice;
                grdInvoice.DataSource = dtInvoice;

                grdInvoice.DataBind();
              //  lblPaymentReferenceNumber.Visible = true;
               // txtPaymentReferenceNumber.Visible = true;
             //   btnMarkPayment.Visible = true;
                lblInvoiceList.Text = "List of Invoices:";
            }
            else
            {
                Session[SessionStore.UnMatchedInvoiceListForRemitter] = null;
                grdInvoice.DataSource = null;
                grdInvoice.DataBind();
                lblInvoiceList.Text = "No Invoices available for reconciliation.";
              //  lblPaymentReferenceNumber.Visible = false;
              //  txtPaymentReferenceNumber.Visible = false;
              //  btnMarkPayment.Visible = false;
            }
        }
        private void GetStatementList()
        {
            User user = (User)Session["CurrentUserVO"];
            Lists lstEntity = new Lists();
            List<Statement> dtStatement = lstEntity.GetUnmatchedStatementsForRemitter(user.CustomerID, user.RemitterID,null);
            Session["RemitUMStatementList"] = dtStatement;
            grdStatement.DataSource = dtStatement;
            grdStatement.DataBind();
        }

        protected void btnSearchStatement_Click(object sender, EventArgs e)
        {
            if (txtSearchStatement.Text != null && txtSearchStatement.Text.Length > 0)
            {
                User user = (User)Session["CurrentUserVO"];
                Lists lstEntity = new Lists();
                List<Statement> dtStatement = lstEntity.GetUnmatchedStatementsForRemitter(user.CustomerID, user.RemitterID, txtSearchStatement.Text);

                List<Statement> dtAlreadyAddedStatement = (List<Statement> )Session["RemitUMStatementList"];
                List<Statement> needForDisplay = new List<Statement>();
             //   foreach(Statement stmt in dtAlreadyAddedStatement)
            //    {
                    if (dtStatement != null)
                    {
                        foreach (Statement stmt1 in dtStatement)
                        {
                            if (!dtAlreadyAddedStatement.Contains(stmt1))
                            {
                                needForDisplay.Add(stmt1);
                            }


                        }
                    }
               // }
                gridStmtSearchResult.DataSource = needForDisplay;
                gridStmtSearchResult.DataBind();
                StatementSearchResultPopup.Show();
            }
        }

        protected void popupClose_Click(object sender, ImageClickEventArgs e)
        {
            StatementSearchResultPopup.Hide();
        }

        protected void btnConfirmRemitter_Click(object sender, EventArgs e)
        {
            
            Button btnConfirm = (Button)sender;
            List<Statement> dtStatement = (List<Statement>)Session["RemitUMStatementList"];
           
            int iRowSelected = 0;
            foreach (GridViewRow row in gridStmtSearchResult.Rows)
            {

                System.Web.UI.HtmlControls.HtmlInputCheckBox chkSelect = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)row.Cells[0].FindControl("chkSelect"));
                if (chkSelect.Checked)
                {
                    //dtStatement.Add(dtSearch.ElementAt(iRowSelected));
                    Statement stmt = new Statement();
                    stmt.referenceNumber = row.Cells[1].Text;
                    stmt.narration1 = row.Cells[3].Text;
                    stmt.amount = Convert.ToDouble(row.Cells[4].Text);
                    dtStatement.Add(stmt);
                }
                iRowSelected++;
            }

            grdStatement.DataSource = dtStatement;
            grdStatement.DataBind();
        }



      

    }
}